import Axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { message } from 'ant-design-vue'
// import qs from 'qs'

interface CustomAxiosRequestConfig extends AxiosRequestConfig {
  hideLoading?: boolean
}

interface BaseResponse<T = any> {
  code: number
  data: T
  msg: string
}

const service = Axios.create({
  baseURL: import.meta.env.VITE_API_DOMAIN as string | undefined,
  timeout: 5000,
})

service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // eslint-disable-next-line no-param-reassign
    // config.data = qs.stringify(config.data) // 转为 formdata 数据格式
    return config
  },
  (error: { message: string }) => {
    message.error(error.message)
  },
)

service.interceptors.response.use(
  (response: AxiosResponse): Promise<any> => {
    const { data } = response
    if (!data) {
      return Promise.reject(data)
    }

    return Promise.resolve(data)
  },
  (error: { message: string }) => {
    message.destroy()
    message.error('网络异常')
    return Promise.reject(error)
  },
)

const request = <T = any>(config: CustomAxiosRequestConfig): Promise<BaseResponse<T>> => {
  return new Promise((resolve, reject) => {
    service
      .request<BaseResponse<T>>(config)
      .then((res: AxiosResponse) => resolve(res.data))
      .catch((err: { message: string }) => reject(err))
  })
}

request.get = (url: string, params?: object): Promise<any> =>
  request({
    method: 'get',
    url,
    params,
  })

request.post = (url: string, params?: object): Promise<any> =>
  request({
    method: 'post',
    url,
    data: params,
  })

export default request
